package com.example.myapplication

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.myapplication.adapter.TradingPointAdapter
import com.example.myapplication.database.PositionRepository
import com.example.myapplication.databinding.ActivityStockDetailBinding
import com.example.myapplication.model.SignalType
import com.example.myapplication.model.TradingSignal
import com.example.myapplication.utils.TradingTimeHelper
import com.example.myapplication.viewmodel.StockViewModel
import kotlinx.coroutines.launch
import com.github.mikephil.charting.charts.ScatterChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.data.ScatterData
import com.github.mikephil.charting.data.ScatterDataSet
import com.github.mikephil.charting.data.CombinedData
import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet
import com.github.mikephil.charting.charts.CombinedChart
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.github.mikephil.charting.highlight.Highlight
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class StockDetailActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityStockDetailBinding
    private val viewModel: StockViewModel by viewModels()
    private lateinit var tradingPointAdapter: TradingPointAdapter
    private lateinit var positionRepository: PositionRepository
    
    private var stockSymbol: String? = null
    private var stockName: String? = null
    private var currentSignal: TradingSignal? = null
    private var currentPrice: Double = 0.0
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityStockDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 获取传入的股票信息
        stockSymbol = intent.getStringExtra("STOCK_SYMBOL")
        stockName = intent.getStringExtra("STOCK_NAME")
        
        // 初始化持仓仓库
        positionRepository = PositionRepository(this)
        
        setupUI()
        setupObservers()
        
        // 加载股票详情
        stockSymbol?.let { symbol ->
            viewModel.loadStockDetail(symbol)
        }
    }
    
    private fun setupUI() {
        // 设置工具栏
        binding.toolbar.title = stockName ?: "股票详情"
        binding.toolbar.setNavigationOnClickListener {
            finish()
        }
        
        
        // 设置买卖点列表
        tradingPointAdapter = TradingPointAdapter()
        binding.tradingPointsRecyclerView.apply {
            adapter = tradingPointAdapter
            layoutManager = LinearLayoutManager(this@StockDetailActivity)
        }
        
        // 配置图表
        setupChart()        
        // 设置下拉刷新
        binding.swipeRefreshLayout.setOnRefreshListener {
            refreshStockDetail()
        }
        
        // 设置下拉刷新的颜色
        binding.swipeRefreshLayout.setColorSchemeResources(
            android.R.color.holo_blue_bright,
            android.R.color.holo_green_light,
            android.R.color.holo_orange_light,
            android.R.color.holo_red_light
        )
    }
    
    /**
     * 刷新股票详情数据
     */
    private fun refreshStockDetail() {
        stockSymbol?.let { symbol ->
            viewModel.loadStockDetail(symbol)
        }
    }
    
    private fun setupChart() {
        binding.lineChart.apply {
            description.isEnabled = false
            setTouchEnabled(true)
            isDragEnabled = true
            setScaleEnabled(true)
            setPinchZoom(true)
            setDrawGridBackground(false)
            
            // 设置CombinedChart的绘制顺序：先绘制线图，再绘制散点图
            drawOrder = arrayOf(
                com.github.mikephil.charting.charts.CombinedChart.DrawOrder.LINE,
                com.github.mikephil.charting.charts.CombinedChart.DrawOrder.SCATTER
            )
            
            xAxis.apply {
                position = XAxis.XAxisPosition.BOTTOM
                setDrawGridLines(false)
                granularity = 1f
            }
            
            axisRight.isEnabled = false
            axisLeft.apply {
                setDrawGridLines(true)
                enableGridDashedLine(10f, 10f, 0f)
            }
            
            // 优化图例显示
            legend.apply {
                isEnabled = true
                verticalAlignment = com.github.mikephil.charting.components.Legend.LegendVerticalAlignment.BOTTOM
                horizontalAlignment = com.github.mikephil.charting.components.Legend.LegendHorizontalAlignment.CENTER
                orientation = com.github.mikephil.charting.components.Legend.LegendOrientation.HORIZONTAL
                setDrawInside(false)
                yOffset = 10f
                xOffset = 0f
                textSize = 9f
                form = com.github.mikephil.charting.components.Legend.LegendForm.CIRCLE
                formSize = 8f
            }
        }
    }
    
    private fun setupObservers() {
        // 存储当前交易信号和价格数据，用于更新图表
        var currentSignal: TradingSignal? = null
        var currentPrices: List<com.example.myapplication.model.StockPrice> = emptyList()
        var currentTradingPoints: List<com.example.myapplication.model.TradingPoint> = emptyList()
        
        // 观察交易信号（仅用于更新图表和买卖点列表）
        viewModel.tradingSignal.observe(this) { signal ->
            currentSignal = signal
            signal?.let {
                // 保存当前价格
                currentPrice = it.price
                
                // 自动保存买入/卖出信号到数据库
                stockSymbol?.let { symbol ->
                    autoSaveSignalToDatabase(symbol, it)
                }
            }
            
            // 更新买卖点列表（包含当前推荐）
            updateTradingPointsList(currentTradingPoints, signal)
            
            // 更新图表，包含推荐买卖点
            if (currentPrices.isNotEmpty()) {
                updateChart(currentPrices, currentTradingPoints, currentSignal)
            }
        }
        
        // 观察价格数据
        viewModel.stockPrices.observe(this) { prices ->
            currentPrices = prices
            if (prices.isNotEmpty()) {
                updateChart(prices, currentTradingPoints, currentSignal)
            }
        }
        
        // 观察历史交易点
        viewModel.tradingPoints.observe(this) { tradingPoints ->
            currentTradingPoints = tradingPoints
            
            // 更新买卖点列表（包含当前推荐的买入/卖出点）
            updateTradingPointsList(tradingPoints, currentSignal)
            
            // 更新图表
            if (currentPrices.isNotEmpty()) {
                updateChart(currentPrices, tradingPoints, currentSignal)
            }
        }
        
        // 观察加载状态
        viewModel.isLoading.observe(this) { isLoading ->
            binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
            // 停止下拉刷新动画
            if (!isLoading) {
                binding.swipeRefreshLayout.isRefreshing = false
            }
        }
        
        // 观察错误信息
        viewModel.error.observe(this) { error ->
            error?.let {
                Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
                viewModel.clearError()
            }
        }
    }
    
    /**
     * 更新K线图，包含价格曲线、历史买卖点和推荐买卖点标记
     */
    private fun updateChart(
        prices: List<com.example.myapplication.model.StockPrice>,
        tradingPoints: List<com.example.myapplication.model.TradingPoint>,
        currentSignal: TradingSignal?
    ) {
        if (prices.isEmpty()) {
            binding.debugDataRange.text = "数据范围: 暂无数据"
            return
        }
        
        // 更新数据范围显示
        val firstDate = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date(prices.first().timestamp))
        val lastDate = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date(prices.last().timestamp))
        binding.debugDataRange.text = "数据范围: $firstDate 至 $lastDate (${prices.size}条)"
        
        // 1. 绘制价格曲线
        val priceEntries = prices.mapIndexed { index, stockPrice ->
            Entry(index.toFloat(), stockPrice.close.toFloat())
        }
        
        val lineDataSet = LineDataSet(priceEntries, "收盘价（真实数据）").apply {
            color = Color.parseColor("#2196F3")
            setCircleColor(Color.parseColor("#2196F3"))
            lineWidth = 2f
            circleRadius = 2f
            setDrawCircleHole(false)
            valueTextSize = 9f
            setDrawFilled(true)
            fillColor = Color.parseColor("#2196F3")
            fillAlpha = 30
            setDrawValues(false)
        }
        
        val lineData = LineData(lineDataSet)
        
        // 2. 创建 CombinedData 并添加价格线
        val combinedData = CombinedData()
        combinedData.setData(lineData)
        
        // 3. 绘制买卖点标记
            val scatterDataSets = mutableListOf<IScatterDataSet>()
            
        // 调试日志
        android.util.Log.d("📊买卖点", "开始绘制买卖点，总数: ${tradingPoints.size}")
        android.util.Log.d("📊买卖点", "价格数据范围: ${if (prices.isNotEmpty()) "${prices.first().timestamp} - ${prices.last().timestamp}" else "empty"}")
        
        // 3.1 历史买入点（绿色圆点，更大更醒目）
            val buyEntries = mutableListOf<Entry>()
        val buyPoints = tradingPoints.filter { it.type == com.example.myapplication.model.PointType.BUY }
        
        android.util.Log.d("📊买卖点", "买入点数量: ${buyPoints.size}")
        
        buyPoints.forEach { point ->
                val index = prices.indexOfFirst { it.timestamp == point.timestamp }
            android.util.Log.d("📊买卖点", "买入点: timestamp=${point.timestamp}, price=${point.price}, index=$index")
                if (index >= 0) {
                    buyEntries.add(Entry(index.toFloat(), point.price.toFloat()))
                android.util.Log.d("📊买卖点", "✅ 添加买入点: index=$index, price=${point.price}")
            } else {
                android.util.Log.w("📊买卖点", "⚠️ 买入点未找到匹配索引: timestamp=${point.timestamp}")
            }
        }
        
        android.util.Log.d("📊买卖点", "实际添加的买入Entry: ${buyEntries.size} 个")
            
            if (buyEntries.isNotEmpty()) {
            val buyDataSet = ScatterDataSet(buyEntries, "● 买入点").apply {
                    setScatterShape(ScatterChart.ScatterShape.CIRCLE)
                scatterShapeSize = 20f // 增大尺寸，更醒目
                    color = Color.parseColor("#00C853") // 亮绿色，更鲜艳
                valueTextColor = Color.parseColor("#00C853")
                    setDrawValues(false)
            }
            scatterDataSets.add(buyDataSet)
            android.util.Log.d("📊买卖点", "✅ 买入点数据集已添加，颜色: #00C853")
            }
            
        // 3.2 历史卖出点（红色圆点，更大更醒目）
            val sellEntries = mutableListOf<Entry>()
        val sellPoints = tradingPoints.filter { it.type == com.example.myapplication.model.PointType.SELL }
        
        android.util.Log.d("📊买卖点", "卖出点数量: ${sellPoints.size}")
        
        sellPoints.forEach { point ->
                val index = prices.indexOfFirst { it.timestamp == point.timestamp }
            android.util.Log.d("📊买卖点", "卖出点: timestamp=${point.timestamp}, price=${point.price}, index=$index")
                if (index >= 0) {
                    sellEntries.add(Entry(index.toFloat(), point.price.toFloat()))
                android.util.Log.d("📊买卖点", "✅ 添加卖出点: index=$index, price=${point.price}")
            } else {
                android.util.Log.w("📊买卖点", "⚠️ 卖出点未找到匹配索引: timestamp=${point.timestamp}")
            }
        }
        
        android.util.Log.d("📊买卖点", "实际添加的卖出Entry: ${sellEntries.size} 个")
            
            if (sellEntries.isNotEmpty()) {
            val sellDataSet = ScatterDataSet(sellEntries, "● 卖出点").apply {
                    setScatterShape(ScatterChart.ScatterShape.CIRCLE)
                scatterShapeSize = 20f // 增大尺寸，更醒目
                    color = Color.parseColor("#FF1744") // 亮红色，更鲜艳
                valueTextColor = Color.parseColor("#FF1744")
                setDrawValues(false)
            }
            scatterDataSets.add(sellDataSet)
            android.util.Log.d("📊买卖点", "✅ 卖出点数据集已添加，颜色: #FF1744")
        }
        
        // 3.3 当前推荐买卖点（方块标记，最醒目）
        currentSignal?.let { signal ->
            val recommendEntries = mutableListOf<Entry>()
            
            // 找到最接近推荐价格的位置（通常是最后一个点）
            val recommendIndex = prices.size - 1
            val recommendPrice = signal.actionPrice ?: signal.price
            
            recommendEntries.add(Entry(recommendIndex.toFloat(), recommendPrice.toFloat()))
            
            if (recommendEntries.isNotEmpty()) {
                // 判断是否为当天
                val today = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date())
                val isToday = signal.signalTime?.startsWith(today) ?: false
                
                // 根据信号类型选择颜色和标签
                val (baseLabel, pointColor) = when {
                    signal.isBuySignal() -> Pair("推荐买入", Color.parseColor("#00E676")) // 超亮绿色
                    signal.isSellSignal() -> Pair("推荐卖出", Color.parseColor("#FF3D00")) // 超亮红色
                    else -> Pair("观望", Color.parseColor("#FFAB00")) // 超亮黄色
                }
                
                // 简化标签
                val label = "⭐ $baseLabel"
                
                scatterDataSets.add(ScatterDataSet(recommendEntries, label).apply {
                    setScatterShape(ScatterChart.ScatterShape.SQUARE) // 方块更醒目
                    scatterShapeSize = 25f  // 更大的尺寸
                    color = pointColor
                    valueTextColor = pointColor
                    setDrawValues(false)
                    valueTextSize = 12f
                })
                
                android.util.Log.d("📊买卖点", "✅ 推荐买卖点已添加: $baseLabel, 颜色: ${String.format("#%06X", 0xFFFFFF and pointColor)}")
            }
            }
            
            // 添加散点数据到 CombinedData
        android.util.Log.d("📊买卖点", "散点数据集总数: ${scatterDataSets.size}")
            if (scatterDataSets.isNotEmpty()) {
            val scatterData = ScatterData(scatterDataSets)
            combinedData.setData(scatterData)
            android.util.Log.d("📊买卖点", "✅ 散点数据已添加到CombinedData")
        } else {
            android.util.Log.w("📊买卖点", "⚠️ 没有散点数据可添加")
        }
        
        // 完全重置图表（清除所有缓存和数据）
        binding.lineChart.clear()
        binding.lineChart.data = null
        binding.lineChart.notifyDataSetChanged()
        binding.lineChart.invalidate()
        
        // 设置新的图表数据
        binding.lineChart.data = combinedData
        
        // 确保散点图在线图上层显示
        binding.lineChart.setDrawOrder(arrayOf(
            CombinedChart.DrawOrder.LINE,
            CombinedChart.DrawOrder.SCATTER
        ))
        
        // 3. 设置X轴显示日期（每次都重新创建，避免缓存）
        val dateFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                val index = value.toInt()
                return if (index >= 0 && index < prices.size) {
                    val timestamp = prices[index].timestamp
                    val formatted = TradingTimeHelper.formatDate(timestamp)
                    formatted
                } else {
                    ""
                }
            }
        }
        
        // 清除旧的formatter
        binding.lineChart.xAxis.valueFormatter = null
        // 设置新的formatter
        binding.lineChart.xAxis.valueFormatter = dateFormatter
        
        binding.lineChart.xAxis.granularity = 1f
        binding.lineChart.xAxis.labelRotationAngle = -45f
        binding.lineChart.xAxis.labelCount = 10
        binding.lineChart.setVisibleXRangeMaximum(30f)
        
        // 强制刷新图表和X轴
        binding.lineChart.notifyDataSetChanged()
        binding.lineChart.invalidate()
        
        // 计算要显示的范围（最后30个数据点）
        val lastIndex = prices.size - 1
        val startIndex = maxOf(0, lastIndex - 29)  // 显示最后30个点
        
        android.util.Log.d("📊图表范围", "总共${prices.size}个点，显示索引${startIndex}到${lastIndex}")
        android.util.Log.d("📊图表数据", """
            |图表数据统计:
            |  价格曲线点数: ${priceEntries.size}
            |  买入点数: ${buyEntries.size}
            |  卖出点数: ${sellEntries.size}
            |  散点数据集数: ${scatterDataSets.size}
            |  是否有散点数据: ${combinedData.scatterData != null}
            |  散点数据集数量: ${combinedData.scatterData?.dataSetCount ?: 0}
        """.trimMargin())
        
        // 延迟滚动和缩放，确保渲染完成
        binding.lineChart.postDelayed({
            // 方法1：直接移动到最右边
            binding.lineChart.moveViewToX(lastIndex.toFloat())
            
            // 方法2：缩放到指定范围
            binding.lineChart.zoom(1f, 1f, lastIndex.toFloat(), 0f)
            
            // 强制刷新
            binding.lineChart.notifyDataSetChanged()
            binding.lineChart.invalidate()
            
            android.util.Log.d("📊图表范围", "✅ 已移动到索引${lastIndex}，图表刷新完成")
        }, 300)
        
        // 4. 添加点击事件，显示买卖点详情
        binding.lineChart.setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
            override fun onValueSelected(e: Entry?, h: Highlight?) {
                if (e != null) {
                    val index = e.x.toInt()
                    
                    // 检查是否点击了推荐买卖点
                    if (currentSignal != null && index == prices.size - 1) {
                        val signal = currentSignal!!
                        val message = when {
                            signal.isBuySignal() -> 
                                "💰 推荐买入点\n建议价格: ¥%.2f\n建议时间: %s\n原因: %s\n信号强度: %d/100"
                                    .format(signal.actionPrice ?: signal.price, signal.actionTime ?: "当前", signal.reason, signal.strength)
                            signal.isSellSignal() -> 
                                "💸 推荐卖出点\n建议价格: ¥%.2f\n建议时间: %s\n原因: %s\n信号强度: %d/100"
                                    .format(signal.actionPrice ?: signal.price, signal.actionTime ?: "当前", signal.reason, signal.strength)
                            else -> 
                                "⚪ 当前观望\n当前价格: ¥%.2f\n原因: %s".format(signal.price, signal.reason)
                        }
                        Toast.makeText(this@StockDetailActivity, message, Toast.LENGTH_LONG).show()
                    } else {
                        // 检查是否点击了历史买卖点
                    val point = tradingPoints.find { 
                        prices.indexOfFirst { p -> p.timestamp == it.timestamp } == index 
                    }
                    point?.let {
                        val dateStr = TradingTimeHelper.formatTradingTime(it.timestamp, "MM-dd HH:mm")
                        val message = when (it.type) {
                            com.example.myapplication.model.PointType.BUY -> 
                                    "🔹 历史买入点 ($dateStr)\n价格: ¥%.2f\n原因: %s\n信号强度: %d/100".format(it.price, it.reason ?: "暂无原因", it.strength)
                            com.example.myapplication.model.PointType.SELL -> 
                                    "🔸 历史卖出点 ($dateStr)\n价格: ¥%.2f\n原因: %s\n信号强度: %d/100".format(it.price, it.reason ?: "暂无原因", it.strength)
                            }
                            Toast.makeText(this@StockDetailActivity, message, Toast.LENGTH_LONG).show()
                        }
                    }
                }
            }
            
            override fun onNothingSelected() {
                // 不处理
            }
        })
        
        // 5. 在日志中输出买卖点信息总结
        val buyCount = tradingPoints.filter { it.type == com.example.myapplication.model.PointType.BUY }.size
        val sellCount = tradingPoints.filter { it.type == com.example.myapplication.model.PointType.SELL }.size
        android.util.Log.d("📊买卖点总结", "====================================")
        android.util.Log.d("📊买卖点总结", "历史买入点: $buyCount 个")
        android.util.Log.d("📊买卖点总结", "历史卖出点: $sellCount 个")
        android.util.Log.d("📊买卖点总结", "散点数据集: ${scatterDataSets.size} 个")
        
        currentSignal?.let { signal ->
            val signalType = when {
                signal.isBuySignal() -> "推荐买入"
                signal.isSellSignal() -> "推荐卖出"
                else -> "持有观望"
            }
            android.util.Log.d("📊买卖点总结", "当前推荐: $signalType，价格: ¥%.2f".format(signal.actionPrice ?: signal.price))
        }
        android.util.Log.d("📊买卖点总结", "====================================")
        
        // 刷新图表 - 先动画再刷新
        binding.lineChart.animateX(800)
    }
    
    /**
     * 更新买卖点列表和统计信息
     * 包含历史买卖点和当前推荐的买入/卖出点
     */
    private fun updateTradingPointsList(
        tradingPoints: List<com.example.myapplication.model.TradingPoint>,
        currentSignal: TradingSignal? = null
    ) {
        // 创建完整的买卖点列表（历史 + 当前推荐）
        val allTradingPoints = mutableListOf<com.example.myapplication.model.TradingPoint>()
        allTradingPoints.addAll(tradingPoints)
        
        // 如果有当前推荐的买入/卖出信号，添加到列表顶部
        currentSignal?.let { signal ->
            if (signal.isBuySignal() || signal.isSellSignal()) {
                val recommendedPoint = com.example.myapplication.model.TradingPoint(
                    timestamp = System.currentTimeMillis(),
                    price = signal.actionPrice ?: signal.price,  // 使用建议操作价格
                    type = if (signal.isBuySignal()) {
                        com.example.myapplication.model.PointType.BUY
                    } else {
                        com.example.myapplication.model.PointType.SELL
                    },
                    reason = "⭐ 当前推荐：${signal.reason}",  // 标记为当前推荐
                    strength = signal.strength
                )
                // 插入到列表最前面（最新推荐）
                allTradingPoints.add(0, recommendedPoint)
            }
        }
        
        if (allTradingPoints.isEmpty()) {
            // 显示空状态
            binding.tradingPointsRecyclerView.visibility = View.GONE
            binding.emptyTradingPointsTextView.visibility = View.VISIBLE
            
            binding.buyPointCountTextView.text = "0"
            binding.sellPointCountTextView.text = "0"
            binding.avgProfitTextView.text = "--"
            
            return
        }
        
        // 显示列表
        binding.tradingPointsRecyclerView.visibility = View.VISIBLE
        binding.emptyTradingPointsTextView.visibility = View.GONE
        
        // 提交数据到适配器（包含当前推荐）
        tradingPointAdapter.submitList(allTradingPoints)
        
        // 统计买卖点数量（包含当前推荐）
        val buyPoints = allTradingPoints.filter { it.type == com.example.myapplication.model.PointType.BUY }
        val sellPoints = allTradingPoints.filter { it.type == com.example.myapplication.model.PointType.SELL }
        
        binding.buyPointCountTextView.text = buyPoints.size.toString()
        binding.sellPointCountTextView.text = sellPoints.size.toString()
        
        // 计算平均收益率（买卖配对，仅统计历史数据，不包含当前推荐）
        val profits = mutableListOf<Double>()
        var buyPoint: com.example.myapplication.model.TradingPoint? = null
        
        // 只用历史数据计算收益，不包含当前推荐
        for (point in tradingPoints) {
            when (point.type) {
                com.example.myapplication.model.PointType.BUY -> {
                    buyPoint = point
                }
                com.example.myapplication.model.PointType.SELL -> {
                    buyPoint?.let { buy ->
                        val profitRate = (point.price - buy.price) / buy.price * 100
                        profits.add(profitRate)
                        buyPoint = null
                    }
                }
            }
        }
        
        // 显示平均收益
        if (profits.isNotEmpty()) {
            val avgProfit = profits.average()
            binding.avgProfitTextView.text = if (avgProfit >= 0) {
                "+%.1f%%".format(avgProfit)
            } else {
                "%.1f%%".format(avgProfit)
            }
            
            // 根据收益设置颜色
            binding.avgProfitTextView.setTextColor(
                if (avgProfit >= 0) Color.parseColor("#00C853") else Color.parseColor("#FF1744")
            )
        } else {
            binding.avgProfitTextView.text = "--"
            binding.avgProfitTextView.setTextColor(Color.parseColor("#FF9800"))
        }
        
        // 输出统计日志
        android.util.Log.d("📊买卖点列表", """
            |====================================
            |买入点: ${buyPoints.size} 个
            |卖出点: ${sellPoints.size} 个
            |配对交易: ${profits.size} 次
            |平均收益: ${if (profits.isNotEmpty()) "%.2f%%".format(profits.average()) else "N/A"}
            |====================================
        """.trimMargin())
    }
    
    /**
     * 自动保存买入/卖出信号到数据库
     */
    private fun autoSaveSignalToDatabase(symbol: String, signal: TradingSignal) {
        lifecycleScope.launch {
            try {
                val name = stockName ?: symbol
                val timestamp = System.currentTimeMillis()
                val quantity = 100 // 默认100股
                
                when {
                    // 买入信号（强烈买入或买入）
                    signal.isBuySignal() -> {
                        val buyPrice = signal.actionPrice ?: signal.price
                        
                        // 检查是否已经有这个时间点的买入记录（避免重复保存）
                        val existingPositions = positionRepository.getOpenBuyPositions(symbol)
                        val alreadyExists = existingPositions.any { 
                            Math.abs(it.timestamp - timestamp) < 60000 // 1分钟内的记录视为重复
                        }
                        
                        if (!alreadyExists) {
                            val buyId = positionRepository.recordBuy(
                                symbol = symbol,
                                stockName = name,
                                price = buyPrice,
                                quantity = quantity,
                                timestamp = timestamp,
                                reason = signal.reason,
                                signalStrength = signal.strength
                            )
                            
                            android.util.Log.d("💰买入记录", "已保存买入信号到数据库: ID=$buyId, 价格=¥$buyPrice, 数量=$quantity")
                            
                            // 刷新持仓信息
                            updatePositionInfo(symbol)
                        }
                    }
                    
                    // 卖出信号（强烈卖出或卖出）
                    signal.isSellSignal() -> {
                        // 检查是否有未平仓的买入记录
                        val openPositions = positionRepository.getOpenBuyPositions(symbol)
                        
                        if (openPositions.isNotEmpty()) {
                            val sellPrice = signal.actionPrice ?: signal.price
                            
                            val sellId = positionRepository.recordSell(
                                symbol = symbol,
                                stockName = name,
                                price = sellPrice,
                                quantity = quantity,
                                timestamp = timestamp,
                                reason = signal.reason,
                                signalStrength = signal.strength
                            )
                            
                            // 计算收益
                            val buyPosition = openPositions.first()
                            val profit = (sellPrice - buyPosition.price) * quantity
                            val profitRate = (sellPrice - buyPosition.price) / buyPosition.price * 100
                            
                            android.util.Log.d("💸卖出记录", "已保存卖出信号到数据库: ID=$sellId, 价格=¥$sellPrice, 收益=¥$profit (${profitRate.format(2)}%)")
                            
                            // 显示卖出提示
                            showSellNotification(buyPosition.price, sellPrice, profit, profitRate)
                            
                            // 刷新持仓信息
                            updatePositionInfo(symbol)
                        } else {
                            android.util.Log.d("💸卖出记录", "没有未平仓的买入记录，跳过卖出信号")
                        }
                    }
                }
                
                // 更新持仓信息显示
                updatePositionInfo(symbol)
                
            } catch (e: Exception) {
                android.util.Log.e("💾数据库", "保存交易信号失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 更新持仓信息显示
     */
    private fun updatePositionInfo(symbol: String) {
        lifecycleScope.launch {
            try {
                val openPositions = positionRepository.getOpenBuyPositions(symbol)
                
                if (openPositions.isNotEmpty()) {
                    val position = openPositions.first()
                    val profit = (currentPrice - position.price) * position.quantity
                    val profitRate = (currentPrice - position.price) / position.price * 100
                    
                    val buyTime = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
                        .format(Date(position.timestamp))
                    
                    val profitText = if (profitRate >= 0) {
                        "+%.2f%% (+¥%.2f)".format(profitRate, profit)
                    } else {
                        "%.2f%% (¥%.2f)".format(profitRate, profit)
                    }
                    
                    val infoText = """
                        买入价格: ¥%.2f (%d股)
                        买入时间: %s
                        当前价格: ¥%.2f
                        持仓收益: %s
                    """.trimIndent().format(
                        position.price,
                        position.quantity,
                        buyTime,
                        currentPrice,
                        profitText
                    )

                    // 持仓信息显示已移除，不再显示
                    
                    android.util.Log.d("📊持仓", "持仓信息已更新: $profitText")
                } else {
                    // 持仓信息显示已移除
                    android.util.Log.d("📊持仓", "无持仓")
                }
            } catch (e: Exception) {
                android.util.Log.e("📊持仓", "更新持仓信息失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 显示卖出提醒通知
     */
    private fun showSellNotification(buyPrice: Double, sellPrice: Double, profit: Double, profitRate: Double) {
        val profitText = if (profit >= 0) {
            "盈利 ¥%.2f (+%.2f%%)".format(profit, profitRate)
        } else {
            "亏损 ¥%.2f (%.2f%%)".format(Math.abs(profit), profitRate)
        }
        
        val message = """
            💸 系统检测到卖出信号
            
            买入价格: ¥%.2f
            卖出价格: ¥%.2f
            交易结果: %s
            
            已自动记录到数据库
        """.trimIndent().format(buyPrice, sellPrice, profitText)
        
        runOnUiThread {
            AlertDialog.Builder(this)
                .setTitle("卖出提醒")
                .setMessage(message)
                .setPositiveButton("确定", null)
                .show()
        }
    }
    
    // Double扩展函数：格式化小数位数
    private fun Double.format(digits: Int) = "%.${digits}f".format(this)
}

